package com.nacos.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @作者: 林江
 * @创建时间: 2023/10/26
 * @功能:
 */
@RestController
public class NacosConsumerController {

    @Resource
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;

    @Value("nacos-provider")
    private String appName;

    /**
     * 基于带有负载均衡的RestTemplate 和 FeignClient 来访问服务提供方
     *
     * @return
     */
    @RequestMapping("/consumer01")
    public String consumer01() {
        // 负载一个服务实列
        ServiceInstance instance = loadBalancerClient.choose(appName);
        String url = String.format("http://%s:%s/%s", instance.getHost(), instance.getPort(), "test");
        // 访问provider服务
        String data = restTemplate.getForObject(url, String.class);
        return "访问到的数据：" + data;
    }
}
